import com.alibaba.fastjson.JSONObject;

public class WYYTool extends Thread{
    ModularMain modularMain;
    DmjMain dmjMain;
    String musicName;
    public WYYTool(ModularMain modularMain1,DmjMain dmjMain1,String musicName1){
        modularMain = modularMain1;
        dmjMain = dmjMain1;
        musicName = musicName1;
    }

    public String getDownloadUrl() throws Exception {
        String res = HttpClient.getInstance().doGet(modularMain.getMusicIdUrl+musicName);
        String musicId = JSONObject.parseObject(res).getJSONObject("result").getJSONArray("songs").getJSONObject(0).getString("id");
        musicName = JSONObject.parseObject(res).getJSONObject("result").getJSONArray("songs").getJSONObject(0).getString("name");
        for (String name : modularMain.downloadingList){
            if (name.equals(musicName)){
                return "";
            }
        }
        for (String name : modularMain.waitList){
            if (name.equals(musicName)){
                return "";
            }
        }
        res = HttpClient.getInstance().doGet(modularMain.dowByMusicIdUrl+musicId);
        String dowurl = JSONObject.parseObject(res).getJSONArray("data").getJSONObject(0).getString("url");
        return dowurl;
    }

    @Override
    public void run() {
        String dowurl = null;
        try {
            dowurl = getDownloadUrl();
            if (dowurl.equals("")){
                return;
            }
            dmjMain.newLogCallback("[点歌机]:",musicName+" 开始下载!");
            modularMain.downloadingList.add(musicName);
        } catch (Exception e) {
            dmjMain.newLogCallback("[点歌机]:",musicName+" 搜索失败!");
            return;
        }
        try {
            HttpClient.getInstance().doDownload(dowurl,"./music/"+musicName+".mp3");
            modularMain.waitList.add(musicName);
            for (int i = 0;i<modularMain.downloadingList.size();i++){
                if (modularMain.downloadingList.get(i).equals(musicName)){
                    modularMain.downloadingList.remove(i);
                    break;
                }
            }
            dmjMain.newLogCallback("[点歌机]:",musicName+" 下载完成!");
        } catch (Exception e) {
            for (int i = 0;i<modularMain.downloadingList.size();i++){
                if (modularMain.downloadingList.get(i).equals(musicName)){
                    modularMain.downloadingList.remove(i);
                    break;
                }
            }
            dmjMain.newLogCallback("[点歌机]:",musicName+" 下载失败!");
            return;
        }
    }
}
